use crate::rtmp::messages;
use crate::rtmp::user_control_messages::{define, errors};
use byteorder::BigEndian;
use bytesio::bytes_reader::BytesReader;

// 事件消息读取结构体，用于解析 RTMP 事件消息
pub struct EventMessagesReader {
    pub reader: BytesReader,
}

impl EventMessagesReader {
    pub fn new(reader: BytesReader) -> Self {
        Self { reader }
    }

    // 解析事件消息
    pub fn parse_event(
        &mut self,
    ) -> Result<messages::define::RtmpMessageData, errors::EventMessagesError> {
        // 读取事件类型
        let event_type = self.reader.read_u16::<BigEndian>()?;
        match event_type {
            define::RTMP_EVENT_SET_BUFFER_LENGTH => self.read_set_buffer_length(),
            define::RTMP_EVENT_STREAM_BEGIN => self.read_stream_begin(),
            define::RTMP_EVENT_STREAM_IS_RECORDED => self.read_stream_is_recorded(),
            _ => Err(errors::EventMessagesError {
                value: errors::EventMessagesErrorValue::UnknowEventMessageTypeError,
            }),
        }
    }

    // 读取设置缓冲区长度事件
    pub fn read_set_buffer_length(
        &mut self,
    ) -> Result<messages::define::RtmpMessageData, errors::EventMessagesError> {
        // 读取流 ID
        let stream_id = self.reader.read_u32::<BigEndian>()?;
        // 缓冲长度
        let ms = self.reader.read_u32::<BigEndian>()?;

        // 返回设置设置缓冲区长度事件数据
        Ok(messages::define::RtmpMessageData::SetBufferLength {
            stream_id,
            buffer_length: ms,
        })
    }

    // 读取流事件
    pub fn read_stream_begin(
        &mut self,
    ) -> Result<messages::define::RtmpMessageData, errors::EventMessagesError> {
        let stream_id = self.reader.read_u32::<BigEndian>()?;
        Ok(messages::define::RtmpMessageData::StreamBegin { stream_id })
    }

    // 读取流是否被记录
    pub fn read_stream_is_recorded(
        &mut self,
    ) -> Result<messages::define::RtmpMessageData, errors::EventMessagesError> {
        let stream_id = self.reader.read_u32::<BigEndian>()?;
        Ok(messages::define::RtmpMessageData::StreamIsRecorded { stream_id })
    }
}
